package com.hxd.mall.utils.open

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.text.SpannableString
import android.text.method.LinkMovementMethod
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.utils.TextUtils
import com.hxd.mall.R
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_is_use
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_name
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstants.Tag_Cancel
import com.hxd.mall.constant.HxdConstants.Tag_Confirm
import com.hxd.mall.constant.HxdConstantsNet
import com.hxd.mall.constant.HxdConstantsNet.userAgreementUrl
import com.hxd.mall.constant.HxdConstantsNet.userPrivacyAgreementUrl
import com.hxd.mall.constant.HxdConstantsNet.userServiceAgreementUrl
import com.hxd.mall.constant.HxdConstantsRouterPath.Common.path_to_webview
import com.hxd.mall.utils.local.*
import com.hxd.mall.utils.local.NavigationUtil.jumpToWebView
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.open.StringUtil.setSpanClick
import com.hxd.threelibrary.umeng.UmClient.QQ
import com.hxd.threelibrary.umeng.UmClient.SAVE_PIC
import com.hxd.threelibrary.umeng.UmClient.WEIXIN
import com.hxd.threelibrary.umeng.UmClient.WEIXIN_CIRCLE
import org.jetbrains.anko.dip
import org.jetbrains.anko.displayMetrics


/**
 * Created by loony on 2018/7/30.
 */
/**
 * 确认取消弹框
 */

private var dialog: Dialog? = null
private var searchDialog: Dialog? = null

fun closeDialog() {
    if (dialog != null && dialog?.isShowing == true)
        dialog?.dismiss()
}

fun Context.showConfirmDialog(
    content: String,
    textCancel: String,
    textConfirm: String,
    cancelColor: Int,
    confirmColor: Int,
    confirmCallBack: () -> Unit,
    cancelCallbacks: () -> Unit
) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_confirm, null)
    val dialogTvHint = inflater.findViewById<TextView>(R.id.dialog_tv_hint)
    val dialogTvCancel = inflater.findViewById<TextView>(R.id.dialog_tv_cancel)
    val dialogTvConfirm = inflater.findViewById<TextView>(R.id.dialog_tv_confirm)

    dialogTvCancel.text = if (textCancel.isEmpty()) "取消" else textCancel
    dialogTvCancel.setTextColor(
        if (cancelColor == 0) ContextCompat.getColor(
            this,
            R.color.color_999999
        ) else cancelColor
    )
    dialogTvConfirm.text = if (textConfirm.isEmpty()) "确认" else textConfirm
    dialogTvConfirm.setTextColor(
        if (confirmColor == 0) ContextCompat.getColor(
            this,
            R.color.color_1153FC
        ) else confirmColor
    )
    dialogTvHint.text = content
    dialogTvCancel.setOnClickListener {
        dialog.dismiss()
        cancelCallbacks()
    }
    dialogTvConfirm.setOnClickListener {
        dialog.dismiss()
        confirmCallBack()
    }
    dialog.setContentView(inflater)
    dialog.show()
}

/**
 * 带title确认取消弹框
 */
fun Context.showConfirmWithTitleDialog(
    title: String,
    content: String,
    confirmText: String,
    confirmCallBack: () -> Unit
): Dialog? {
    dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_confirm_with_title, null)
    val dialogTvTitle = inflater.findViewById<TextView>(R.id.dialog_tv_title)
    val dialogTvHint = inflater.findViewById<TextView>(R.id.dialog_tv_hint)
    val dialogTvCancel = inflater.findViewById<TextView>(R.id.dialog_tv_cancel)
    val dialogTvConfirm = inflater.findViewById<TextView>(R.id.dialog_tv_confirm)

    dialogTvTitle.text = title
    dialogTvHint.text = content
    if (confirmText.isNotEmpty())
        dialogTvConfirm.text = confirmText
    dialogTvCancel.setOnClickListener {
        dialog?.dismiss()
    }
    dialogTvConfirm.setOnClickListener {
        dialog?.dismiss()
        confirmCallBack()
    }
    dialog?.setContentView(inflater)
    dialog?.show()

    return dialog
}


/**
 * 活动提示弹框
 *
 * url:图片地址
 * path:跳转h5的地址
 */
fun Context.showPicDialog(url: String, path: String): Dialog? {
    dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_pic_layout, null)
    val layout_content = inflater.findViewById<RelativeLayout>(R.id.layout_content)
    val iv_piv = inflater.findViewById<ImageView>(R.id.iv_piv)
    val iv_close = inflater.findViewById<ImageView>(R.id.iv_close)

    val params = layout_content.layoutParams
    params.width = displayMetrics.widthPixels * 4 / 5
    params.height = displayMetrics.widthPixels * 3 / 4
    layout_content.layoutParams = params

    iv_close.setOnClickListener {
        dialog?.dismiss()
    }
    iv_piv.setOnClickListener {
        dialog?.dismiss()
        routerNavigation(path_to_webview, key_web_url, path)
    }
    dialog?.setContentView(inflater)
    dialog?.show()
    return dialog
}

/**
 * 首页自定义协议弹窗提示
 */
fun Context.showConfirmWithCancelTitleDialog(
    confirmCallBack: () -> Unit
): Dialog? {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_cancel_confirm_with_title, null)
    inflater.findViewById<TextView>(R.id.tv_control).setOnClickListener(null)
    val dialogTvCancel = inflater.findViewById<TextView>(R.id.dialog_tv_cancel)
    val dialogTvConfirm = inflater.findViewById<TextView>(R.id.dialog_tv_confirm)
    val tv_control = inflater.findViewById<TextView>(R.id.tv_control)

    tv_control.movementMethod = LinkMovementMethod.getInstance()
    tv_control.text = SpannableString(getString(R.string.home_tip_contro)).apply {
        setSpanClick(this, 10, 22) {
            jumpToWebView("锦鲤口袋用户注册协议", userAgreementUrl)
        }
        setSpanClick(this, 23, 35) {
            jumpToWebView("锦鲤口袋用户服务协议", userServiceAgreementUrl)
        }
        setSpanClick(this, 36, 48) {
            jumpToWebView("锦鲤口袋用户隐私协议", userPrivacyAgreementUrl)
        }
    }
    dialogTvCancel.setOnClickListener {
        dialog.dismiss()
        StackManageUtil.closeAll()
    }
    dialogTvConfirm.setOnClickListener {
        dialog.dismiss()
        confirmCallBack()
    }
    dialog.setContentView(inflater)
    dialog.show()

    return dialog
}


/**
 * 带背景确认取消弹框
 */
fun Context.showConfirmWithTitleNewBgDialog(
    content: String,
    confirmText: String,
    confirmCallBack: (Boolean) -> Unit
): Dialog? {

    if (searchDialog != null && searchDialog?.isShowing==true){
        searchDialog?.dismiss()
    }

    searchDialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_confirm_with_title_newbg, null)
    val dialogTvHint = inflater.findViewById<TextView>(R.id.dialog_tv_hint)
    val dialogTvCancel = inflater.findViewById<TextView>(R.id.dialog_tv_cancel)
    val dialogTvConfirm = inflater.findViewById<TextView>(R.id.dialog_tv_confirm)

    dialogTvHint.text = content
    if (confirmText.isNotEmpty())
        dialogTvConfirm.text = confirmText
    dialogTvCancel.setOnClickListener {
        sendPoint(search_pop_up_cancel_button_click)
        searchDialog?.dismiss()
        searchDialog = null
        confirmCallBack(false)
    }
    dialogTvConfirm.setOnClickListener {
        sendPoint(search_pop_up_quick_search_button_click)
        searchDialog?.dismiss()
        searchDialog = null
        confirmCallBack(true)
    }
    searchDialog?.setContentView(inflater)
    searchDialog?.show()

    sendPoint(search_pop_up_view)
    return searchDialog
}

/**
 * ocr弹框
 */
fun Context.showCameraDialog(
    initPicker: () -> Unit,
    block: () -> Unit,
    confirmCallBack: () -> Unit
) {
    initPicker()
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_camera_choice, null)
    val dialogTvCamera = inflater.findViewById<TextView>(R.id.dialog_tv_camera)
    val dialogTvLocal = inflater.findViewById<TextView>(R.id.dialog_tv_local)
    val dialogTvCancel = inflater.findViewById<TextView>(R.id.dialog_tv_cancel)
    dialogTvCancel.setOnClickListener { dialog.dismiss() }
    dialogTvCamera.setOnClickListener {
        dialog.dismiss()
        block()
    }
    dialogTvLocal.setOnClickListener {
        dialog.dismiss()
        confirmCallBack()
    }
    dialog.setContentView(inflater)
    dialog.show()
}

/**
 * 放弃申请弹框
 */
fun Context.showGiveUpDialog(callbacks: (String, String) -> Unit) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_sign, null)

    val dialogTvCancel = inflater.findViewById<TextView>(R.id.dialog_tv_cancel)
    val dialogTvGiveUp = inflater.findViewById<TextView>(R.id.dialog_tv_give_up)
    val dialogTvMoneyLow = inflater.findViewById<TextView>(R.id.dialog_tv_money_low)
    val dialogTvFeeHigh = inflater.findViewById<TextView>(R.id.dialog_tv_fee_high)
    val dialogTvTerm = inflater.findViewById<TextView>(R.id.dialog_tv_term)
    val dialogTvComplex = inflater.findViewById<TextView>(R.id.dialog_tv_complex)
    val dialogTvOtherReason = inflater.findViewById<TextView>(R.id.dialog_tv_other_reason)
    val dialogEtText = inflater.findViewById<EditText>(R.id.dialog_et_text)

    dialogTvMoneyLow.setOnClickListener { setTag(dialogTvMoneyLow, this) }
    dialogTvFeeHigh.setOnClickListener { setTag(dialogTvFeeHigh, this) }
    dialogTvTerm.setOnClickListener { setTag(dialogTvTerm, this) }
    dialogTvComplex.setOnClickListener { setTag(dialogTvComplex, this) }
    dialogTvOtherReason.setOnClickListener { setTag(dialogTvOtherReason, this) }
    dialogTvCancel.setOnClickListener {
        dialog.dismiss()
    }
    dialogTvGiveUp.setOnClickListener {
        val mContent = StringBuffer()
        if (dialogTvMoneyLow.tag == Tag_Confirm) {
            mContent.append(dialogTvMoneyLow.text.toString() + ";")
        }
        if (dialogTvFeeHigh.tag == Tag_Confirm) {
            mContent.append(dialogTvFeeHigh.text.toString() + ";")
        }
        if (dialogTvTerm.tag == Tag_Confirm) {
            mContent.append(dialogTvTerm.text.toString() + ";")
        }
        if (dialogTvComplex.tag == Tag_Confirm) {
            mContent.append(dialogTvComplex.text.toString() + ";")
        }
        if (dialogTvOtherReason.tag == Tag_Confirm) {
            mContent.append(dialogTvOtherReason.text.toString())
        }
        if (!mContent.isEmpty()) {
            val text = if (mContent.toString().endsWith(";")) mContent.toString().substring(
                0,
                mContent.toString().length - 1
            ) else mContent.toString()
            callbacks(text, dialogEtText.text.toString())
            dialog.dismiss()
        }
    }
    dialog.setContentView(inflater)
    dialog.show()
}

private fun setTag(textView: TextView, context: Context) {
    if (textView.tag == Tag_Cancel) {
        textView.tag = Tag_Confirm
        textView.setTextColor(ContextCompat.getColor(context, R.color.color_FF7B02))
        textView.setBackgroundResource(R.drawable.dialog_bg_ff7b02)
    } else if (textView.tag == Tag_Confirm) {
        textView.tag = Tag_Cancel
        textView.setTextColor(ContextCompat.getColor(context, R.color.color_444444))
        textView.setBackgroundResource(R.drawable.dialog_bg_eeeeee)
    }
}

/**
 * Dialog ok(知道了 样式)
 */
fun Context.showConfirmTipDialog(content: String, title: String? = "", callbacks: () -> Unit) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_confirm_tip, null)
    val dialogTvHint = inflater.findViewById<TextView>(R.id.dialog_tv_hint)
    val dialogLayoutOk = inflater.findViewById<View>(R.id.layout_dialog_ok)
    val dialogLayoutConfirm = inflater.findViewById<TextView>(R.id.dialog_tv_confirm)
    if (!title.isNullOrEmpty()) {
        dialogLayoutConfirm.text = title
    }
    dialogTvHint.text = content
    dialogLayoutOk.setOnClickListener {
        dialog.dismiss()
        callbacks()
    }
    dialog.setContentView(inflater)
    dialog.show()
}

@SuppressLint("ClickableViewAccessibility")
fun Context.showBreakContractDialog(
    title: String?,
    content: ArrayList<String>?,
    desc: String? = "",
    callbacks: () -> Unit
) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_break_contract, null)
    inflater.layoutParams = ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT
    )
    val dialogTvTitle = inflater.findViewById<TextView>(R.id.dialog_tv_title)
    val dialogTvContent = inflater.findViewById<LinearLayout>(R.id.dialog_tv_content)
    val dialogLayoutOk = inflater.findViewById<View>(R.id.layout_dialog_ok)
//    val dialogScrollView = inflater.findViewById<ScrollView>(R.id.dialog_scrollview)
//    var mFlag = false
//    dialogScrollView.setOnTouchListener { _, _ ->
//        // 判断scrollview 滑动到底部
//        if (dialogScrollView.getChildAt(0).measuredHeight - dialogScrollView.height <= dialogScrollView.scrollY) {
//            mFlag = true
//        }
//        false
//    }
    inflater.findViewById<View>(R.id.view_dialog_bg).setOnClickListener {
        dialog.dismiss()
    }
    if (!TextUtils.isEmpty(title)) {
        dialogTvTitle.text = title
    }
    dialogLayoutOk.setOnClickListener {
        //if(dialogScrollView.getChildAt(0).measuredHeight - dialogScrollView.height <= dialogScrollView.scrollY || mFlag){
        dialog.dismiss()
        callbacks()
//        } else ToastUtil.showToast("请阅读完该协议")
    }

    val list = mutableListOf<String>()
    if (null != content) {
        list.addAll(content)
    }
    if (desc != null && desc.isNotEmpty()) {
        list.add(0, desc)
    }
    if (list.isNotEmpty()) {
        for (i in list.indices) {
            val textView = TextView(this)
            textView.text = list[i]
            textView.setTextColor(ContextCompat.getColor(this, R.color.color_444444))
            textView.textSize = 12f
            textView.setPadding(0, UIUtil.dip2px(7), 0, 0)
            dialogTvContent.addView(textView)
        }
    }

    dialog.run {
        setContentView(inflater)
        show()
    }
}

/**
 * 客服电话弹窗
 */
fun Context.showCallPhoneDialog(
    title: String,
    content: String? = null,
    cancleStr: String? = null,
    confirStr: String? = null,
    confirmCallBack: () -> Unit
) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_call_phone, null)
    val dialogTvHint = inflater.findViewById<TextView>(R.id.dialog_tv_hint)
    val contenttv = inflater.findViewById<TextView>(R.id.content)
    val dialogTvCancel = inflater.findViewById<TextView>(R.id.dialog_tv_cancel)
    val dialogTvConfirm = inflater.findViewById<TextView>(R.id.dialog_tv_confirm)

    if (!android.text.TextUtils.isEmpty(title)) {
        dialogTvHint.text = title
    }
    if (!android.text.TextUtils.isEmpty(content)) {
        contenttv.text = content
    }
    if (!android.text.TextUtils.isEmpty(cancleStr)) {
        dialogTvCancel.text = cancleStr
    }
    if (!android.text.TextUtils.isEmpty(confirStr)) {
        dialogTvConfirm.text = confirStr
    }
    dialogTvCancel.setOnClickListener {
        dialog.dismiss()
//        cancelCallbacks()
    }
    dialogTvConfirm.setOnClickListener {
        dialog.dismiss()
        confirmCallBack()
    }
    dialog.setContentView(inflater)
    dialog.show()
}

/**
 * 粉丝信息
 */
fun Context.showFunInfoDialog(
    photoPath: String,
    nick: String,
    income: String,
    registerTime: String
) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_funs_info_layout, null)
    val close = inflater.findViewById<ImageView>(R.id.close)
    close.setOnClickListener {
        dialog.dismiss()
    }
    dialog.setContentView(inflater)
    dialog.show()
}

/**
 * 分享
 */
fun Context.showShareDialog(callbacks: (Int) -> Unit) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_share_layout, null)
    val weChatShare = inflater.findViewById<View>(R.id.weChatShare)
    val momentShare = inflater.findViewById<View>(R.id.momentShare)
    val qqShare = inflater.findViewById<View>(R.id.qqShare)
    val cancel = inflater.findViewById<View>(R.id.cancel)
    cancel.setOnClickListener { dialog.dismiss() }
    weChatShare.setOnClickListener {
        dialog.dismiss()
        callbacks(WEIXIN)
    }
    momentShare.setOnClickListener {
        dialog.dismiss()
        callbacks(WEIXIN_CIRCLE)
    }
    qqShare.setOnClickListener {
        dialog.dismiss()
        callbacks(QQ)
    }
    dialog.setContentView(inflater)
    dialog.show()
}

/**
 * 邀请好友分享
 */
fun Context.showShareFriendDialog(callbacks: (Int) -> Unit) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_share_layout, null)
    val savePic_layout = inflater.findViewById<View>(R.id.savePic_layout)
    savePic_layout.visibility = View.VISIBLE
    val weChatShare = inflater.findViewById<View>(R.id.weChatShare)
    val momentShare = inflater.findViewById<View>(R.id.momentShare)
    val qqShare = inflater.findViewById<View>(R.id.qqShare)
    qqShare.visibility = View.GONE
    val cancel = inflater.findViewById<View>(R.id.cancel)
    cancel.setOnClickListener { dialog.dismiss() }
    weChatShare.setOnClickListener {
        dialog.dismiss()
        callbacks(WEIXIN)
    }
    momentShare.setOnClickListener {
        dialog.dismiss()
        callbacks(WEIXIN_CIRCLE)
    }
    savePic_layout.setOnClickListener {
        dialog.dismiss()
        callbacks(SAVE_PIC)
    }
    dialog.setContentView(inflater)
    dialog.show()
}

//关闭弹窗 防止内存泄漏，意外关闭时需要调用
fun disssDialog() {
    dialog?.dismiss()
}

/**
 * 商品详情页-分享()
 * @param type 1分享  2 授权
 */
fun Context.showDetailShareDialog(content: String, type: Int? = 1, callbacks: () -> Unit) {
    val dialog = Dialog(this, R.style.TranslucentBackground)
    val inflater = LayoutInflater.from(this).inflate(R.layout.dialog_share, null)
    val content_layout = inflater.findViewById<RelativeLayout>(R.id.content_layout)
    val dialogContent = inflater.findViewById<TextView>(R.id.dialog_tv_content)
    val dialogLayoutOk = inflater.findViewById<TextView>(R.id.layout_dialog_ok)
    val tv_dialog_copy = inflater.findViewById<TextView>(R.id.tv_dialog_copy)
    val cancel = inflater.findViewById<View>(R.id.cancel)
    val title = inflater.findViewById<View>(R.id.title)
    dialogContent.text = content
    val layoutParams = content_layout.layoutParams
    when (type) {
        1 -> {
            title.visibility = View.GONE
            tv_dialog_copy.visibility = View.VISIBLE
            dialogLayoutOk.text = "分享给微信好友"
            dialogContent.gravity = Gravity.START
            tv_dialog_copy.setOnClickListener {
                setPrimaryClip(it?.context!!, content)
                dialog.dismiss()
            }
            layoutParams.width = content_layout.context.displayMetrics.widthPixels * 3 / 4
            layoutParams.height = content_layout.context.dip(400)
        }
        2 -> {
            layoutParams.width = content_layout.context.displayMetrics.widthPixels * 2 / 3

            title.visibility = View.VISIBLE
            tv_dialog_copy.visibility = View.GONE
            dialogLayoutOk.text = "去授权"
            dialogContent.gravity = Gravity.CENTER
        }
    }
    content_layout.layoutParams = layoutParams

    dialogLayoutOk.setOnClickListener {
        dialog.dismiss()
        callbacks()
    }
    cancel.setOnClickListener {
        dialog.dismiss()
    }
    dialog.setContentView(inflater)
    dialog.show()
}

fun showDialogSingChoic(activity: Context, message: String, items: Array<String>, checkItem: Int, onClickListener: (Int) -> Unit) {
    var index = 0
    index = checkItem
    var alerDialog: AlertDialog? = null
    alerDialog = AlertDialog.Builder(activity, 0)
        .setTitle(message)
        .setNegativeButton("确认") { _, _ ->
            onClickListener(index)
            alerDialog?.dismiss()
        }.setCancelable(false).setSingleChoiceItems(items, checkItem) { _, which ->
            index = which
        }.setPositiveButton(
            "取消"
        ) { _, _ ->
            alerDialog?.dismiss()
        }.create()

    alerDialog.show()
    alerDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.GRAY)
    alerDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLUE)
}
